package com.usian.comment.service.Impl;

import com.usian.comment.feign.ApUserFeign;
import com.usian.comment.service.CommentRepayService;
import com.usian.model.comment.dtos.CommentRepayDto;
import com.usian.model.comment.dtos.CommentRepayLikeDto;
import com.usian.model.comment.dtos.CommentRepaySaveDto;
import com.usian.model.comment.pojos.*;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import sun.plugin2.applet.AWTAppletSecurityManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ApUserFeign apUserFeignl;

    /***
     * 评论回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1:检查参数

        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize()==null){
            dto.setSize(10);
        }
        //2.按照文章id过滤，设置分页和排序

        Query query = new Query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
        //3.数据封装返回
        //3.1 用户未登录 加载数据
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.okResult(commentRepayList);
        }
        //3.2 用户已登录 加载数据 判断当前用户点赞了哪些评论
        List<String> idList = commentRepayList.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1=Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(
                user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        ArrayList<ApCommentRepayVo> resultList = new ArrayList<>();
        if (commentRepayList!=null&&apCommentRepayLikes!=null){
            commentRepayList.stream().forEach(x->{
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();

                BeanUtils.copyProperties(x,apCommentRepayVo);
                for (ApCommentRepayLike apCommentRePayLike :apCommentRepayLikes){
                    if (x.getId().equals(apCommentRePayLike.getCommentRepayId())){
                        apCommentRepayVo.setOperation((short)0);
                        break;
                    }
                }
                resultList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(resultList);
        }else {
            ResponseResult.okResult(commentRepayList);
        }

        return null;
    }

    /***
     * 保存回复内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1:检查参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2:判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3:保存评论
        ApUser apUser = apUserFeignl.findUserById(user.getId());
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前登录信息有误");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        //4:更新评论回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /***
     * 点赞 回复内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //1:检查参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2:判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay!=null&&dto.getOperation()==0){
            //点赞 更新评论的点赞数
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);
            //保存 app评论信息点赞
            ApCommentRepayLike apCommentRepayLike=new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);
        }else  if (apCommentRepay!=null&&dto.getOperation()==1){
            //取消点赞
            //评论的点赞数量-1
            apCommentRepay.setLikes(apCommentRepay.getLikes()<0?0:apCommentRepay.getLikes()-1);
            mongoTemplate.save(apCommentRepay);
            //更新app评论信息点赞
            //删除
            Query query=Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId()));
            mongoTemplate.remove(query,ApCommentRepayLike.class);
        }
        HashMap <String,Object> result=new HashMap<>();
        result.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(result);
    }
}
